package com.service.impl;

import com.alibaba.fastjson.JSON;
import com.dao.FloorDao;
import com.pojo.Floor;
import com.pojo.RoomType;
import com.service.FloorService;
import com.util.JedisPoolUtils;
import com.util.RedisKey;
import com.vo.FloorVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * @author mornd
 * @date 2020/11/24 - 9:49
 */
@Service
@Transactional
public class FloorServiceImpl implements FloorService {
    @Autowired
    private FloorDao floorDao;

    public List<Floor> findFloorList(FloorVo floorVo) {
        return floorDao.findFloorList(floorVo);
    }

    public int addFloor(Floor floor) {
        int count = floorDao.addFloor(floor);
        //清空redis缓存数据
        if (count > 0){
            JedisPoolUtils.getJedis().del(RedisKey.FLOOR_LIST);
            findFloorByRedis();
        }
        return count;
    }

    public int updateFloor(Floor floor) {
        int count = floorDao.updateFloor(floor);
        //清空redis缓存数据
        if (count > 0){
            JedisPoolUtils.getJedis().del(RedisKey.FLOOR_LIST);
            findFloorByRedis();
        }
        return count;
    }

    @Override
    public String findFloorByRedis() {
        //创建jedis对象
        Jedis jedis = JedisPoolUtils.getJedis();
        //拿取房型集合的键
        String floorList = jedis.get(RedisKey.FLOOR_LIST);
        //判断是否为空
        if(StringUtils.isEmpty(floorList)){
            //从数据库中查询数据
            List<Floor> floors = findFloorList(null);
            //将数据添加至缓存中
            floorList = jedis.set(RedisKey.FLOOR_LIST, JSON.toJSONString(floors));
        }
        return floorList;
    }
}
